﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AntsCode.StorageClientExtensions;
using Microsoft.WindowsAzure;
using System.Data.Services.Client;
using AntsCode.StorageClientExtensions.Denormalization;
using System.Linq.Expressions;

namespace TestHarnessWebRole.Data
{
    public class TestTableServiceContext : XTableServiceContext
    {
        public TestTableServiceContext(string baseAddress, StorageCredentials credentials) :
            base(baseAddress, credentials)
        {
            this.IgnoreResourceNotFoundException = true;
            this.MergeOption = System.Data.Services.Client.MergeOption.OverwriteChanges;
            this.DenormalizingEntity += OnDenormalizingEntity;
            this.DenormalizationError += OnDenormalizationError;
        }

        void OnDenormalizationError(object sender, DenormalizationErrorEventArgs e)
        {
            // TODO: Log the error
            throw new NotImplementedException();
        }

        void OnDenormalizingEntity(object sender, DenormalizingEntityEventArgs e)
        {
            DenormalizationRules rules = e.Rules;

            rules.Add<Company, Customer>(
                s => s.Name,
                d => d.CompanyName,
                (s, d) => d.CompanyId == s.RowKey && d.PartitionKey == "Customers",
                (s, d) => s.RowKey == d.CompanyId && s.PartitionKey == "Companies",
                false);
        }

        public XTableServiceQuery<Location> Location
        {
            get
            {
                return this.CreateQuery<Location>("Location");
            }
        }

        public XTableServiceQuery<Company> Company
        {
            get
            {
                return this.CreateQuery<Company>("Company");
            }
        }

        public XTableServiceQuery<Customer> Customer
        {
            get
            {
                return this.CreateQuery<Customer>("Customer");
            }
        }

        public XTableServiceQuery<Order> Order
        {
            get
            {
                return this.CreateQuery<Order>("Order");
            }
        }
    }
}